 

昨天問到,若 input 為 [1,2,3] 那麼 output 為 [2,1,3] 還是 [1,3,2] ?
我們使用 迭代/遞迴 來解這個題目



    class Solution:
        def swapPairs(self, head: ListNode) -> ListNode:
    #       先儲存一個
            dummy = ListNode(0)
            dummy.next = head
            current = dummy
            while current.next != None and current.next.next != None:
    #           first 跟 second 儲存準備交換的 Node
                first = current.next
                second = current.next.next
    #           先把 first Node 指向 second 的下一個Node
                first.next = second.next
    #           先把 second Node 指向 first 的下一個Node 
                second.next = first 
    #           先把 second Node 指向 即將變成第一個點的 second 的下一個Node 
                current.next = second        
    #           把 current 跳到 first 的位置
                current = first
            return dummy.next
 
我們需要輸出兩兩交換位置後的 linked list:
 
利用此遞迴關係,我們不斷將問題化簡成較短的 list ,直到 list 長度為 0 或 1 時,我們終於可以知道答案:
綜合以上發現我們可以列出遞迴關係式。為了方便表示,此處用一般的 list 進行表示,並且以 node_i+1 表示 node_i 所指向的下一個節點:

其中,前兩種 case 為終止條件,第三個 case 為遞迴關係。
有了遞迴關係式,我們便可以撰寫程式:
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
#       head 指向第一個位置,若為空,則回傳 None
				if head is None: return None
#       second 指向第二個位置,若為空,則回傳 None        
        second = head.next
        if second is None: return head
#       rest 指向剩下的位置 (就是第二個位置之後)
        rest = second.next
        
#       交換前 [head, second, rest...] -> 交換後 [second, head, rest...]
#       第二個指向第一個,第一個指向剩下的
        second.next = head
        head.next = self.swapPairs(rest)
        
        return second